<?php
class IO_Image
{
    //This class is provided to manipulated image
    //Make a thumbnail image, default width = 100, keep image ratio
    //arguments: $args
    //$args['filepath']: path to image file
    //$args['thumb_width']: path to image file
    //$args['extlimit']: yes: limit extension (default)
    //$args['limitedext']: array of limited extension: i.e array(".gif",".jpg", ...)
    //Output file is added thumb_ in filename, the same directory
    
    function MakeThumbImage($args) 
    {
        extract($args);
        if (!$thumb_width)
        {
            $thumb_width = 100;
        }
    	
    	if (!$extlimit)
    	{
    	    $extlimit = "yes";
    	}
    	if (!$limitedext)
    	{
    	    $limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");
    	}
    	
    	$fileInfo = getimagesize($filepath);
    	$width = $fileInfo[0];
    	$height = $fileInfo[1];
    	$file_type = $fileInfo['mime'];
    	$file_name = basename($filepath);
    	$file_size = filesize($filepath);
    	
    	//check the file's extension
    	$ext = strrchr($file_name,'.');
    	$ext = strtolower($ext);
    	if (($extlimit == "yes") && (!in_array($ext,$limitedext))) 
    	{
    		return "Wrong file extension.";
    	}
    	//so, whats the file's extension?
    	$getExt = explode ('.', $file_name);
    	$file_ext = $getExt[count($getExt)-1];
    	
    	//the new width variable
    	$ThumbWidth = $thumb_width;
    	/////////////////////////////////
    	// CREATE THE THUMBNAIL //
    	////////////////////////////////
    	//keep image type
    	if($file_size)
    	{
    		if($file_type == "image/pjpeg" || $file_type == "image/jpeg")
    		{
    			$new_img = imagecreatefromjpeg($filepath);
    		}
    		elseif	($file_type == "image/x-png" || $file_type == "image/png")
    		{
    			$new_img = imagecreatefrompng($filepath);
    		}
    		elseif	($file_type == "image/gif")
    		{
    			$new_img = imagecreatefromgif($filepath);
    		}
    		//list the width and height and keep the height ratio.
    		
    		//calculate the image ratio
    		$imgratio=$width/$height;
    		if ($imgratio>1)
    		{
    			$newwidth = $ThumbWidth;
    			$newheight = $ThumbWidth/$imgratio;
    		}
    		else
    		{
    			$newheight = $ThumbWidth;
    			$newwidth = $ThumbWidth*$imgratio;
    		}
    		//function for resize image.
    		if (function_exists(imagecreatetruecolor))
    		{
    			$resized_img = imagecreatetruecolor($newwidth,$newheight);
    		}
    		else
    		{
    			return "Error: Please make sure you have GD library ver 2+";
    		}
    		//the resizing is going on here!
    		imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    		//finally, save the image
    		ImageJpeg ($resized_img,dirname($filepath) . "/thumb_$file_name");
    		ImageDestroy ($resized_img);
    		ImageDestroy ($new_img);
    	}
    	return "OK";
    }
}